package com.example.maoguolin

import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

class MainActivity : AppCompatActivity() {

    // 定义变量
    private lateinit var editTextMin: EditText
    private lateinit var editTextMax: EditText
    private lateinit var buttonCalculate: Button
    private lateinit var buttonStop: Button
    private lateinit var textViewResult: TextView
    private var handler = Handler()
    private var isCalculating = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 初始化视图组件
        editTextMin = findViewById(R.id.editTextMin)
        editTextMax = findViewById(R.id.editTextMax)
        buttonCalculate = findViewById(R.id.buttonCalculate)
        buttonStop = findViewById(R.id.buttonStop)
        textViewResult = findViewById(R.id.textViewResult)

        // 计算按钮的点击事件
        buttonCalculate.setOnClickListener {
            val min = editTextMin.text.toString().toIntOrNull() ?: 0
            val max = editTextMax.text.toString().toIntOrNull() ?: 0
            calculatePrimes(min, max)
        }

        // 停止按钮的点击事件
        buttonStop.setOnClickListener {
            isCalculating = false // 点击时将标志设置为 false
            buttonStop.isEnabled = false // 禁用停止按钮
        }
    }

    private fun calculatePrimes(min: Int, max: Int) {
        isCalculating = true
        textViewResult.text = ""
        buttonStop.isEnabled = true // 启用停止按钮

        Thread {
            val primes = mutableListOf<Int>()
            for (i in min..max) {
                if (!isCalculating) {
                    break // 如果 isCalculating 为 false，直接跳出循环
                }

                if (isPrime(i)) {
                    primes.add(i)
                    handler.post { textViewResult.append("$i\n") }
                    saveToFile(primes)
                }

                // 这里可以添加一个短暂的延迟，以防止 UI 线程被压垮
                Thread.sleep(10) // 控制 CPU 使用率
            }

            // 更新UI
            handler.post {
                buttonStop.isEnabled = false // 计算结束后禁用停止按钮
            }
            isCalculating = false // 标志位设置为 false，表示计算已结束
        }.start()
    }

    private fun isPrime(num: Int): Boolean {
        if (num < 2) return false
        for (i in 2 until num) {
            if (num % i == 0) return false
        }
        return true
    }

    private fun saveToFile(primes: List<Int>) {
        val file = File(filesDir, "primes.txt")
        try {
            FileOutputStream(file, true).use { output ->
                for (prime in primes) {
                    output.write("$prime\n".toByteArray())
                }
            }
        } catch (e: IOException) {
            Log.e("MainActivity", "Error writing to file", e)
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main_menu, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.menu_history) {
            startActivity(Intent(this, SecondActivity::class.java))
            return true
        }
        return super.onOptionsItemSelected(item)
    }
}